package other.edan.system.plm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.data.model.MajorProject__c;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.edan.system.client.EdanK3Utils;
import other.edan.system.utils.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: 同步PLM大项目日期信息
 * @Author: 黎炎松
 * @Date: 2024/12/9 09:31
 */
@RestApi(baseUrl = "/xsy/bigProject")
public class SyncBigProject implements ScheduleJob, FutureTask {

    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步PLM大项目日期信息 ==> ";

    /**
     * 手动触发同步
     * @param
     * @return
     */
    @RestMapping(value = "/handerSync", method = RequestMethod.GET)
    public Result handerSync() {
        LOGGER.debug("手动触发同步");
        return startSyncTrDate();
    }

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        LOGGER.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            LOGGER.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        startSyncTrDate();
    }

    public static void main(String[] args) {
        HCXObjectService.isLocal = true;
        SyncBigProject syncBigProject = new SyncBigProject();
        syncBigProject.startSyncTrDate();
    }


    public Result startSyncTrDate() {
        try {
            LOGGER.info(LOGGER_MSG + "开始处理");
            ResultBody response = EdanK3Utils.sendPost(null, EdanK3Utils.GET_BIG_PROJECT_URL, "");
            if (!Objects.equals(response.getCode(), "200")) {
                LOGGER.info(LOGGER_MSG + "查询大项目日期数据异常: " + response.getMessage());
                return Result.error("Abnormal query of date data for major projects: " + response.getMessage());
            }

            List<JSONObject> trDateList = JSONArray.parseArray(response.getResult().toString(), JSONObject.class);
            if (trDateList.size() <= 0) {
                LOGGER.info(LOGGER_MSG + "没有需要处理的数据");
                return Result.error("There is no data that needs to be processed");
            }

            // 查询系统中匹配的大项目数据
            String projectNumbers = trDateList.stream().map(v -> "'" + v.getString("ProjectNumber") + "'").collect(Collectors.joining(","));
            String sql = String.format("select id,name,syTRContent__c,tr0ActualCompletionTime__c,tr1ActualCompletionTime__c,tr2ActualCompletionTime__c,tr3ActualCompletionTime__c," +
                    "tr4ActualCompletionTime__c from majorProject__c where name in (%s)", projectNumbers);
            Map<String, JSONObject> crmDataMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getString("name"), e1 -> e1, (e, e1) -> e));
            LOGGER.info(LOGGER_MSG + "crmDataMap = " + crmDataMap);

            // 修改数据
            Set<String> sets = crmDataMap.keySet();
            List<JSONObject> filterList = trDateList.stream().filter(v -> sets.contains(v.getString("ProjectNumber"))).collect(Collectors.toList());
            List<MajorProject__c> crmUpList = new ArrayList<>();
            List<String> upCodeList = new ArrayList<>();
            for (JSONObject trDate : filterList) {

                // 旧数据
                JSONObject project = crmDataMap.get(trDate.getString("ProjectNumber"));
                String tr0 = project.getLong("tr0ActualCompletionTime__c") != null ?  HCDateUtils.longToString(project.getLong("tr0ActualCompletionTime__c"), HCDateUtils.FORMAT) : "";
                String tr1 = project.getLong("tr1ActualCompletionTime__c") != null ?  HCDateUtils.longToString(project.getLong("tr1ActualCompletionTime__c"), HCDateUtils.FORMAT) : "";
                String tr2 = project.getLong("tr2ActualCompletionTime__c") != null ?  HCDateUtils.longToString(project.getLong("tr2ActualCompletionTime__c"), HCDateUtils.FORMAT) : "";
                String tr3 = project.getLong("tr3ActualCompletionTime__c") != null ?  HCDateUtils.longToString(project.getLong("tr3ActualCompletionTime__c"), HCDateUtils.FORMAT) : "";
                String tr4 = project.getLong("tr4ActualCompletionTime__c") != null ?  HCDateUtils.longToString(project.getLong("tr4ActualCompletionTime__c"), HCDateUtils.FORMAT) : "";


                // 新数据
                String new_tr0 = trDate.getString("TR0");
                String new_tr1 = trDate.getString("TR1");
                String new_tr2 = trDate.getString("TR2");
                String new_tr3 = trDate.getString("TR3");
                String new_tr4 = trDate.getString("TR4");

                List<String> tipList = new ArrayList<>();
                if (!Objects.equals(tr0, new_tr0)) tipList.add(String.format("[TR0实际完成时间] 由'%s' 修改为 '%s'", tr0, new_tr0));
                if (!Objects.equals(tr1, new_tr1)) tipList.add(String.format("[TR1实际完成时间] 由'%s' 修改为 '%s'", tr1, new_tr1));
                if (!Objects.equals(tr2, new_tr2)) tipList.add(String.format("[TR2实际完成时间] 由'%s' 修改为 '%s'", tr2, new_tr2));
                if (!Objects.equals(tr3, new_tr3)) tipList.add(String.format("[TR3实际完成时间] 由'%s' 修改为 '%s'", tr3, new_tr3));
                if (!Objects.equals(tr4, new_tr4)) tipList.add(String.format("[TR4实际完成时间] 由'%s' 修改为 '%s'", tr4, new_tr4));

                // 字段赋值
                MajorProject__c upMajorProject = new MajorProject__c();
                upMajorProject.setId(project.getLong("id"));
                upMajorProject.setTr0ActualCompletionTime__c(DateTools.dateStrToLong(new_tr0));
                upMajorProject.setTr1ActualCompletionTime__c(DateTools.dateStrToLong(new_tr1));
                upMajorProject.setTr2ActualCompletionTime__c(DateTools.dateStrToLong(new_tr2));
                upMajorProject.setTr3ActualCompletionTime__c(DateTools.dateStrToLong(new_tr3));
                upMajorProject.setTr4ActualCompletionTime__c(DateTools.dateStrToLong(new_tr4));

                // 设置修改的内容
                if (tipList.size() > 0) {
                    upCodeList.add(trDate.getString("ProjectNumber"));

                    String newTips = String.format("%s : %s;", HCDateUtils.longToString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm"), StringUtils.join(tipList, " , "));
                    String syTRContent = project.getString("syTRContent__c");
                    upMajorProject.setSyTRContent__c(StringUtils.isNotBlank(syTRContent) ? syTRContent + "\n" + newTips : newTips);
                }

                crmUpList.add(upMajorProject);
                if (crmUpList.size() > 50) {
                    HCXObjectService.updateBatch(crmUpList);
                    crmUpList.clear();
                }
            }
            HCXObjectService.updateBatch(crmUpList);

            LOGGER.info(LOGGER_MSG + "处理成功");

            String msg = "处理成功(本次没有更新的项目数据)";
            if (upCodeList.size() > 0) {
                msg = String.format("处理成功(本次更新修改的大项目编号: %s)", StringUtils.join(upCodeList, ","));
            }
            return Result.success(msg,"");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(LOGGER_MSG + "获取异常:" + e.getMessage());
            return Result.error("获取异常: " + e.getMessage());
        }
    }


}
